<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\PlatformMoneyRecord;
use app\common\model\ShopMember;
use think\Config;
use think\Db;
use think\Exception;
use think\Queue;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Recharge extends Backend
{

    protected $relationSearch = true;

    /**
     * Recharge模型对象
     * @var \app\common\model\Recharge
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Recharge;
        $this->assign('statusMap'  , \app\common\model\Recharge::$statusMap);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $list = $this->model->with(['shop','agents'])->where($where)->order($sort, $order)->paginate($limit);

            if (!isset($filter['status'])){ //全统计
                $ljwc = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',3)->sum('recharge.money'); //累计完成
                $ljdlcz = $this->model->with(['shop','agents'])->where($where)->where('recharge.status','in',[1,2,3])->sum('recharge.money');//累计代理商充值
                $ljptcz = $this->model->with(['shop','agents'])->where($where)->where('recharge.status','in',[2,3])->sum('recharge.money');//累计平台充值
                $dddlscz = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',0)->sum('recharge.money');//等待代理商充值
                $ddptqr= $this->model->with(['shop','agents'])->where($where)->where('recharge.status',1)->sum('recharge.money');//等待平台确认
                $sjqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',2)->sum('recharge.money');//等待商家确认
                $count = [['name'=>'累计完成充值','value'=>$ljwc],
                    ['name'=>'等待代理商充值','value'=>$dddlscz],
                    ['name'=>'累计代理充值','value'=>$ljdlcz],
                    ['name'=>'等待平台充值','value'=>$ddptqr],
                    ['name'=>'累计平台充值','value'=>$ljptcz],
                    ['name'=>'等待商家确认','value'=>$sjqr]
                ];
            }else{ //按类别统计
                if ($filter['status'] == 3){
                    $ljwc = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',3)->sum('recharge.money'); //累计完成
                    $count = [['name'=>'累计完成充值','value'=>$ljwc],
                        ['name'=>'等待代理商充值','value'=>0],
                        ['name'=>'累计代理充值','value'=>0],
                        ['name'=>'等待平台充值','value'=>0],
                        ['name'=>'累计平台充值','value'=>0],
                        ['name'=>'等待商家确认','value'=>0]
                    ];

//                    $count = [['name'=>'累计完成充值','value'=>$ljwc],['name'=>'累计待确认','value'=>0],['name'=>'等待代理商充值','value'=>0],['name'=>'等待平台充值','value'=>0],['name'=>'等待商家确认','value'=>0]];
                }elseif ($filter['status'] == 0){
                    $ljdqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',0)->sum('recharge.money');//累计待确认
                    $count = [['name'=>'累计完成充值','value'=>0],
                        ['name'=>'等待代理商充值','value'=>$ljdqr],
                        ['name'=>'累计代理充值','value'=>0],
                        ['name'=>'等待平台充值','value'=>0],
                        ['name'=>'累计平台充值','value'=>0],
                        ['name'=>'等待商家确认','value'=>0]
                    ];

//                    $count = [['name'=>'累计完成充值','value'=>0],['name'=>'累计待确认','value'=>$ljdqr],['name'=>'等待代理商充值','value'=>$ljdqr],['name'=>'等待平台充值','value'=>0],['name'=>'等待商家确认','value'=>0]];
                }elseif ($filter['status'] == 1){
                    $ddptqr= $this->model->with(['shop','agents'])->where($where)->where('recharge.status',1)->sum('recharge.money');//等待平台确认
                    $count = [['name'=>'累计完成充值','value'=>0],
                        ['name'=>'等待代理商充值','value'=>0],
                        ['name'=>'累计代理充值','value'=>0],
                        ['name'=>'等待平台充值','value'=>$ddptqr],
                        ['name'=>'累计平台充值','value'=>0],
                        ['name'=>'等待商家确认','value'=>0]
                    ];

//                    $count = [['name'=>'累计完成充值','value'=>0],['name'=>'累计待确认','value'=>$ddptqr],['name'=>'等待代理商充值','value'=>0],['name'=>'等待平台充值','value'=>$ddptqr],['name'=>'等待商家确认','value'=>0]];
                }elseif ($filter['status'] == 2){
                    $sjqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',2)->sum('recharge.money');//等待商家确认
                    $count = [['name'=>'累计完成充值','value'=>0],
                        ['name'=>'等待代理商充值','value'=>0],
                        ['name'=>'累计代理充值','value'=>0],
                        ['name'=>'等待平台充值','value'=>0],
                        ['name'=>'累计平台充值','value'=>0],
                        ['name'=>'等待商家确认','value'=>$sjqr]
                    ];

//                    $count = [['name'=>'累计完成充值','value'=>0],['name'=>'累计待确认','value'=>$sjqr],['name'=>'等待代理商充值','value'=>0],['name'=>'等待平台充值','value'=>0],['name'=>'等待商家确认','value'=>$sjqr]];
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items(),'extend'=>['count'=>$count]);
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 确认充值
     * @return string
     * @throws \think\Exception
     */
    public function confirm($ids = null)
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $row = $this->model->get(['id'=>$params['id']])->toArray();
                if (!$row) {
                    $this->error(__('No Results were found'));
                }
                Db::startTrans();
                try {
                    $result = $this->model->update(['id'=>$params['id'],'status'=>2,'platform_record'=>$params['reocrd_images'],'platformtime'=>time()]);
                    //平台收益记录
                    PlatformMoneyRecord::create(['type'=>2,'detail_type'=>PlatformMoneyRecord::DETAIL_TYPE_SHOP_RECHARGE,'money'=>$row['money'],'remark'=>$row['id'],'createtime'=>time()]);
                    Db::commit();
                    //获取商家的管理员
                    $shop_admin = ShopMember::where(['is_admin'=>1,'is_del'=>0,'shop_id'=>$row['shop_id']])->find();
                    if (!empty($shop_admin)){
                        Queue::push(\app\job\Message::class,[
                            'member_id'=>$shop_admin->member_id,
                            'template_id'=>config('wechat_gzh')['gzh_template']['recharge_success'],
                            'pagepath'=>'pages/shop/record/invest',
                            'data'=>[
                                'amount1'=>$row['money'],
                                'amount2'=>"",
                                'character_string4'=>$row['id'],
                                'time5'=>date('Y-m-d H:i'),
                                'thing11'=>"平台"
                            ]
                        ],'message');
                    }
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("id", $ids);
        return $this->view->fetch();
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload('uploads/recharge/');
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }

}
